package com.ruoyi.web.core.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Nancal.com Inc.
 * Copyright (c) 2021- All Rights Reserved.
 *
 * @Classname MyMetaObjectHandler
 * @Author yangtz
 * @Date 2023/5/21 19:44
 * @Description
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
        if (StrUtil.isNotEmpty(getLoginUsername())) {
            this.strictInsertFill(metaObject, "createBy", () -> getLoginUsername(), String.class); // 起始版本 3.3.3(推荐)
        }
        if (StrUtil.isNotEmpty(getLoginUsername())) {
            this.strictUpdateFill(metaObject, "updateBy", () -> getLoginUsername(), String.class); // 起始版本 3.3.3(推荐)
        }
        log.info("ebd insert fill ....");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        if (StrUtil.isNotEmpty(getLoginUsername())) {
            this.strictUpdateFill(metaObject, "updateBy", () -> getLoginUsername(), String.class); // 起始版本 3.3.3(推荐)
        }
        log.info("ebd update fill ....");
    }

    private String getLoginUsername() {
        Authentication authentication = SecurityUtils.getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) principal;
            SysUser user = loginUser.getUser();
            if (ObjectUtil.isNotNull(user)) {
                return user.getUserName();
            }
        }
        return "";
    }
}